<template>
  <div class="register-container">
    <h2>注册</h2>
    <form @submit.prevent="handleRegister">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required/>
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required/>
      </div>
      <div class="button-container">
        <button type="submit">注册</button>
        <button type="button" @click="clearForm">清空</button>
        <button type="button" @click="goToLogin">登录</button>
      </div>
    </form>
    <ErrorMessageModal v-model:visible="showErrorModal" :message="errorMessage"/>
  </div>
</template>

<script>
import axios from 'axios';
import ErrorMessageModal from './ErrorMessageModal.vue';

export default {
  data() {
    return {
      username: '',
      password: '',
      showErrorModal: false,
      errorMessage: ''
    };
  },
  components: {
    ErrorMessageModal
  },
  methods: {
    handleRegister() {
      // 处理注册逻辑
      console.log('注册用户名:', this.username);
      console.log('注册密码:', this.password);
      // 在此处添加实际的注册请求逻辑
      axios.post('http://localhost:4000/api/register', {username: this.username, password: this.password})
          .then(response => {
            console.log('注册成功:', response.data);
            this.$router.push('/login'); // 导航到登录界面
            // 处理成功的注册逻辑，例如存储令牌
          })
          .catch(error => {
            console.error('注册失败:', error);
            // 处理注册失败逻辑
            if (error.response && error.response.status === 409) {
              this.errorMessage = '注册失败：' + error.response.data.message; // 设置错误信息
            } else {
              this.errorMessage = '注册失败，请稍后再试。'; // 设置其他注册失败信息
            }
            this.showErrorModal = true; // 显示模态框
          });
    },
    clearForm() {
      this.username = '';
      this.password = '';
    },
    goToLogin() {
      this.$router.push('/login');
    }
  }
};
</script>

<style scoped>
.register-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

h2 {
  text-align: center;
}

form div {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #00914D;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #007A3F;
}

.button-container {
  display: flex;
  justify-content: space-between;
  /* Distribute space between buttons */
  gap: 10px;
  /* Add space between buttons */
}

.button-container button {
  width: auto;
  /* Allow buttons to size based on content */
  flex-grow: 1;
  /* Allow buttons to grow and fill the container */
}
</style>